<?php

class loginAuthActions extends sfActions {

    public function executeVerifyAuthentication(sfWebRequest $request){
        $platform = $request->getParameter('platform');
        $continue = $request->getParameter('continue');

        /* si ambos parametros están definidos */
        if(isset($platform) && isset($continue)){
            /* verificamos que los datos recogidos via url sean válidos */
            $c = new Criteria();
            $c->add(PlataformaPeer::SLUG, $platform);
            $obj_platform = PlataformaPeer::doSelectOne($c);
            if(!is_object($obj_platform)){
                return $this->setTemplate('notValid');
            }

            $file_get_contents = @file_get_contents(urldecode($continue));
            if($file_get_contents === FALSE){
                return $this->setTemplate('notValid');
            }
        }

        /* si el usuario no està autenticado, se solicita autenticación */
        if(!$this->getUser()->isAuthenticated()){
            $this->platform = $platform;
            $this->continue = urldecode($continue);
            return $this->setTemplate('verifyAuthentication');
        }else{
            /* verificar si ha llegado con parametros o sin parametros */
            /* si ha llegado con parametros es porque viene de otro sistema */
            if(isset($platform) && isset($continue)){
                /* verifica si ya se encuentra asociado a la plataforma */
                /* si no se encuentra asociado, solicita aceptar terminos y condiciones de uso */
                return $this->verifyPlatform($platform, $continue);
            }else{
                /* si ha llegado sin parametros es porque desea ingresar a practil cuentas */
                return $this->redirect('@account');
            }
        }
    }

    private function verifyPlatform($platform, $continue){
        $current_user = $this->getUser()->getAttribute('current_user');

        $c = new Criteria();
        $c->add(PlataformaPeer::SLUG, $platform);
        $obj_platform = PlataformaPeer::doSelectOne($c);

        $platform_id = $obj_platform->getId();

        /* verificar si existe en plataforma para ver si lo actualizamos*/
        if(!$this->platformUserExists($current_user->getPlataforma(), $platform_id)){
            /* El usuario NO existe en la plataforma */
           $this->platform = $platform_id;
           $this->continue = $continue;
            switch($platform_id){
                /* aceptor */
                case '1':
                    return $this->setTemplate('termsAceptor');break;
                /* comande */
                case '2':
                    return $this->setTemplate('termsComande');break;
                /* contactunity */
                case '3':
                    return $this->setTemplate('termsContactunity');break;
                /* human scorecard */
                case '4':
                    return $this->setTemplate('termsHumanScorecard');break;
                /* opinics */
                case '5':
                    return $this->setTemplate('termsOpinics');break;
            }
        }else{
            return $this->redirect(urldecode($continue));
        }
    }

    private function platformUserExists($platforms,$platform){
        /* si existe devuelve true, sino devuelve false */
        /* Formato de array plataforma: 1-2-3-5 */
        $return = false;
        if($platforms!=""){
            $list = explode('-', $platforms);
            for($i=0 ; $i<count($list) ; $i++){
                if($list[$i]==$platform){
                    $return = true;
                }
            }
        }
        return $return;
    }

    public function executeLoginForm(sfWebRequest $request){

    }

    public function executeAcceptPlatform(sfWebRequest $request){
        $platform = $request->getParameter('hdPlatform');
        $continue = $request->getParameter('hdContinue');
        $current_user = $this->getUser()->getAttribute('current_user');

        $c = new Criteria();
        $c->add(UsuarioPeer::ID, $current_user->getId());
        $object = UsuarioPeer::doSelectOne($c);
        $object->setPlataforma($object->getPlataforma().$platform.'-');
        $object->save();

        $current_user = $this->getUser()->setAttribute('current_user', $object);

        if($platform!='' && $continue!=''){
            $this->redirect(urldecode($continue));
        }else{
            $this->redirect('@loginAuth');
        }
    }

    public function executeLogin(sfWebRequest $request){
        $email = $request->getParameter('email');
        $password = $request->getParameter('password');
        $platform = $request->getParameter('hdPlatform');
        $continue = $request->getParameter('hdContinue');

        $c = new Criteria();
        $c->add(UsuarioPeer::EMAIL, $email);
        $c->add(UsuarioPeer::PASSWORD, md5($password));
        $usuario = UsuarioPeer::doSelectOne($c);
        if(is_object($usuario)){
            $this->getUser()->setAuthenticated(true);
            $this->getUser()->setAttribute('current_user', $usuario);
        }else{
            $this->getUser()->setFlash('msg', 'Datos ingresados incorrectos, intente nuevamente');
        }
        if($platform!='' && $continue!=''){
            $this->redirect('@loginAuth?platform='.$platform.'&continue='.urlencode($continue));
        }else{
            $this->redirect('@loginAuth');
        }
    }

    public function executeLogout(sfWebRequest $request){
        $this->getUser()->setAuthenticated(false);
        $this->getUser()->getAttributeHolder()->clear();
        $this->redirect('@loginAuth');
    }

}